package mo.leetcode_top;

import mo.common.ListNode;

import java.util.Arrays;

public class L2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        ListNode next = res;
        int add = 0;
        while (l1 != null && l2 != null) {
            next.next = new ListNode((l1.val + l2.val + add) % 10);
            next = next.next;
            add = (l1.val + l2.val + add) / 10;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null) {
            next.next = new ListNode((l1.val + add) % 10);
            next = next.next;
            add = (l1.val + add) / 10;
            l1 = l1.next;
        }
        while (l2 != null) {
            next.next = new ListNode((l2.val + add) % 10);
            next = next.next;
            add = (l2.val + add) / 10;
            l2 = l2.next;
        }
        if (add == 1) {
            next.next = new ListNode(1);
        }
        return res.next;
    }


    public static void main(String[] args) {
        L2 test = new L2();
        ListNode l1 = ListNode.convertList2ListNode(Arrays.asList(9, 9, 9, 9, 9, 9, 9));
        ListNode l2 = ListNode.convertList2ListNode(Arrays.asList(9, 9, 9, 9));
        ListNode res = test.addTwoNumbers(l1, l2);
        while (res != null) {
            System.out.println(res.val);
            res = res.next;
        }
    }
}
